# Created by 黄景涛
# DATE: 2025/3/4
import os.path
import yaml
import ruamel.yaml as ru_yaml

from config.settings import ROOT_PATH
from utils.log.logger import logger


def read_yaml(relative_file_path: str) -> dict:
    """ 加载文件内容 """
    file_path = os.path.join(ROOT_PATH, relative_file_path)
    with open(file_path, mode='r', encoding='utf8') as f:
        content = yaml.safe_load(f)
    return content


def read_yaml_key(relative_file_path: str, key: str):
    content = read_yaml(relative_file_path)

    dk = DictKey(key)
    return dk.get(content)


def update_yaml_key(relative_file_path: str, key: str, new_val):
    """ 更新key """
    file_path = os.path.join(ROOT_PATH, relative_file_path)
    r_yaml = ru_yaml.YAML()
    r_yaml.preserve_quotes = True
    r_yaml.indent(mapping=2, sequence=4, offset=2)

    with open(file_path, 'r', encoding='utf-8') as f:
        content = r_yaml.load(f)

    dk = DictKey(key)
    old_value = dk.get(content)
    new_content = dk.update(content, new_val)

    with open(file_path, 'w', encoding='utf-8') as f:
        r_yaml.dump(new_content, f)

    success_msg = f"更新成功， key: {key:<30} \t新值：{new_val} \t旧值：{old_value}"
    logger.warning(success_msg)


def delete_yaml_key(relative_file_path: str, key: str):
    """ 删除key """
    file_path = os.path.join(ROOT_PATH, relative_file_path)
    r_yaml = ru_yaml.YAML()
    r_yaml.preserve_quotes = True
    r_yaml.indent(mapping=2, sequence=4, offset=2)

    with open(file_path, 'r', encoding='utf-8') as f:
        content = r_yaml.load(f)

    dk = DictKey(key)
    old_value = dk.get(content)
    new_content = dk.delete(content)

    with open(file_path, 'w', encoding='utf-8') as f:
        r_yaml.dump(new_content, f)

    success_msg = f"删除成功， key: {key:<30} \t值：{old_value}"
    logger.warning(success_msg)


class DictKey:

    def __init__(self, key: str):
        self.key = key

    def parser_key(self, data: dict):
        """ 解析多种key写法，eg: auth.cookie;  eg: url_routes.routes[1].b"""

        cur_key_name = ""
        cur_sequence_idx = ""
        int_ok = False
        value = data

        try:
            for i in range(len(self.key)):
                char = self.key[i]
                if char == "." and self.key[i - 1] == "]":
                    continue

                elif char == ".":
                    value = value.get(cur_key_name)
                    cur_key_name = ""
                elif char == "[":
                    value = value.get(cur_key_name)
                    cur_key_name = ""
                    int_ok = True
                elif int_ok and (char.isdigit() or char == "-"):
                    cur_sequence_idx += char
                elif char == "]":
                    value = value[int(cur_sequence_idx)]
                    cur_sequence_idx = ""
                    int_ok = False
                else:
                    cur_key_name += char
        except:
            raise ValueError(f"{self.key}格式错误")
        else:
            return value, cur_key_name

    def get(self, data: dict):
        value, cur_key_name = self.parser_key(data)
        return value.get(cur_key_name)

    def update(self, data: dict, new_value) -> dict:
        value, cur_key_name = self.parser_key(data)
        value[cur_key_name] = new_value
        return data

    def delete(self, data: dict) -> dict:
        value, cur_key_name = self.parser_key(data)
        value.pop(cur_key_name)
        return data


if __name__ == '__main__':
    data = read_yaml('config/config.yaml')
    print(data)
    print(read_yaml_key('config/config.yaml', 'auth.smart_saas.cookie'))
    update_yaml_key('config/config.yaml', "url_routes.routes[-1].xxx2.c", '心智1')
    update_yaml_key('config/config.yaml', "cc", 'AAC')
    delete_yaml_key('config/config.yaml', "cc")

